﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Media;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using D5ScannerFPCWrapper;
using DevExpress.XtraEditors.DXErrorProvider;
using DPFP;
using DPFP.Capture;
using DPFP.Processing;
using DPFP.Verification;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Keyboard;
using DevExpress.Data.Filtering;
using DevExpress.Data.Filtering.Helpers;
using DevExpress.ExpressApp.Security.Strategy;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraEditors.Controls;
using TransLogger.Module.BusinessObjects;
using PopupContainerControl = DevExpress.XtraEditors.PopupContainerControl;


namespace Submitter
{
    public partial class Form1 : XtraForm, DPFP.Capture.EventHandler
    {

        private D5ScannerFPC _fingerReader;

        private IObservable<long> _timer;
        private Driver _driver;
        private Vehicle _vehicle;
        private OperationHistory _operationHistory;
        private UnitOfWork _unitOfWork;

        private string _dataDirectory;
        private const string tyreStatesFileName = "tyrestates.txt";
        private const string safetyInstrumentFileName = "safetyInstrument.txt";
        private List<string> _tyreStates = new List<string>();
        private List<string> _safetyInstruments = new List<string>();
        private PopupContainerControl _popupActualPassengerCount;
        private IDisposable _refreshObserver;
        private PopupContainerControl _popupFreePassengerCount;
        private PopupContainerControl _popupLprNumber;
        private PopupContainerControl _popupTyre;
        private XPCollection<RawLprRecord> collection;
        private bool _fingerOn;
        private IDisposable _fingerReaderObserver;
        private SoundPlayer _retrySoundPlayer = new SoundPlayer();
        private SoundPlayer _thankYouSoundPlayer = new SoundPlayer();
        private XPCollection _drivers;
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public Form1()
        {
            InitializeComponent();
            _dataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            numberKeyboard1.AttachTo(this);
        }



        public string LicenseNumber
        {
            get
            {
                if (textEditProvience.EditValue == null || comboBoxEditLprNumber.EditValue == null)
                {
                    return null;
                }

                return (string)textEditProvience.EditValue + comboBoxEditLprNumber.EditValue ?? string.Empty;
            }
            set
            {
                if (!string.IsNullOrEmpty(value) && value.Length > 1)
                {
                    textEditProvience.EditValue = value.Substring(0, 1);
                    comboBoxEditLprNumber.EditValue = value.Substring(1);
                }
                else
                {
                    textEditProvience.EditValue = "川";
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ShowOnSecondaryScreen();
            InitRefreshTimer();
            InitFingerprintReader();
            InitProvienceCharacters();
            //InitCityLetters();
            SetupToast();
            SetupValidationRule();
            LoadStates();
            BeginSession();
            //HookupEvent();
            CreatePopup();
            InitSoundPlayer();
            SetupValidationRule();
            LoadDrivers();
        }

        private void LoadDrivers()
        {
            _drivers = new XPCollection(_unitOfWork, typeof(Driver));
            _drivers.Load();

            this.comboBoxEditIdCardNumber.Properties.DataSource = _drivers;
            this.comboBoxEditDriverFileNumber.Properties.DataSource = _drivers;
            this.textEditDriverName.Properties.DataSource = _drivers;
        }

        private void InitSoundPlayer()
        {
            _retrySoundPlayer = new SoundPlayer("retry.wav");
            _retrySoundPlayer.Load();
            _thankYouSoundPlayer = new SoundPlayer("thanks.wav");
            _thankYouSoundPlayer.Load();
        }

        private void ShowOnSecondaryScreen()
        {
            this.TopMost = !Debugger.IsAttached;
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
        }

        private void InitProvienceCharacters()
        {
            var proviences = new[] { "川" };
            textEditProvience.Properties.Items.AddRange(proviences);
        }

        private void CreatePopup()
        {
            _popupActualPassengerCount = new PopupContainerControl();
            _popupActualPassengerCount.Controls.Add(new NumberOnlyXtraUserControl());
            // actualPassengerCount.Properties.PopupControl = _popupActualPassengerCount;

            _popupFreePassengerCount = new PopupContainerControl();
            _popupFreePassengerCount.Controls.Add(new NumberOnlyXtraUserControl());
            // textEditFreePassengerCount.Properties.PopupControl = _popupFreePassengerCount;

            _popupLprNumber = new PopupContainerControl();
            _popupLprNumber.Controls.Add(new NumberKeyboardUserControl());
            // comboBoxEditLprNumber.Properties.PopupControl = _popupLprNumber;

            _popupTyre = new PopupContainerControl();
            _popupTyre.Controls.Add(new NumberKeyboardUserControl());




            if (!string.IsNullOrEmpty(Properties.Settings.Default.NumberKeyboardSize))
            {
                var szStr = TypeDescriptor.GetConverter(typeof(Size));
                var sz = (Size)szStr.ConvertFromString(Properties.Settings.Default.NumberKeyboardSize);
                _popupLprNumber.Size = sz;
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.NumberOnlyKeyboardSize))
            {
                var szStr = TypeDescriptor.GetConverter(typeof(Size));
                var sz = (Size)szStr.ConvertFromString(Properties.Settings.Default.NumberOnlyKeyboardSize);
                _popupActualPassengerCount.Size = sz;
                _popupFreePassengerCount.Size = sz;
            }


            //actualPassengerCount.QueryPopUp += ActualPassengerCountOnQueryPopUp;
            //textEditFreePassengerCount.QueryPopUp += ActualPassengerCountOnQueryPopUp;
            //actualPassengerCount.QueryResultValue += ActualPassengerCountOnQueryResultValue;
            //textEditFreePassengerCount.QueryResultValue += ActualPassengerCountOnQueryResultValue;
            //comboBoxEditLprNumber.QueryPopUp += ActualPassengerCountOnQueryPopUp;
            //comboBoxEditLprNumber.QueryResultValue += ActualPassengerCountOnQueryResultValue;
        }

        private void ActualPassengerCountOnQueryResultValue(object sender, QueryResultValueEventArgs queryResultValueEventArgs)
        {
            var pce = (sender as PopupContainerEdit);
            dynamic popup = pce.Properties.PopupControl.Controls[0];

            queryResultValueEventArgs.Value = popup.EditValue;
        }


        private void ActualPassengerCountOnQueryPopUp(object sender, CancelEventArgs cancelEventArgs)
        {
            var pce = (sender as PopupContainerEdit);
            dynamic popup = pce.Properties.PopupControl.Controls[0];

            popup.EditValue = pce.EditValue;

            //var pce = (sender as PopupContainerEdit);
            //pce.Properties.PopupControl.Height = 125;
            //pce.Properties.PopupControl.Width = 125;

        }

        private void SetupValidationRule()
        {
            var lengthValidation = new TextLengthValidationRule() { ErrorText = "车牌号码长度为6", Length = 6 };
            this.dxValidationProvider1.SetValidationRule(comboBoxEditLprNumber, lengthValidation);

            var notEmptyRule = new ConditionValidationRule();
            notEmptyRule.ConditionOperator = DevExpress.XtraEditors.DXErrorProvider.ConditionOperator.IsNotBlank;
            notEmptyRule.ErrorText = "不能为空";
            this.dxValidationProvider1.SetValidationRule(this.actualPassengerCount, notEmptyRule);
            this.dxValidationProvider1.SetValidationRule(this.textEditFreePassengerCount, notEmptyRule);

        }

        private void LoadStates()
        {
            if (File.Exists(TyreStateFilePath))
            {
                _tyreStates.AddRange(File.ReadAllLines(TyreStateFilePath));
            }

            if (File.Exists(SafetyInstrumentFilePath))
            {
                _safetyInstruments.AddRange(File.ReadAllLines(SafetyInstrumentFilePath));
            }

            this.tyreState.Properties.Items.AddRange(_tyreStates);
            this.textEditSafetyInstrument.Properties.Items.AddRange(_safetyInstruments);
        }

        private string TyreStateFilePath
        {
            get { return Path.Combine(_dataDirectory, tyreStatesFileName); }
        }

        private string SafetyInstrumentFilePath
        {
            get { return Path.Combine(_dataDirectory, safetyInstrumentFileName); }
        }

        private void SetupToast()
        {
            ToastNotification.ToastFont = new Font("Tahoma", 20);
            ToastNotification.DefaultToastPosition = eToastPosition.MiddleCenter;
            //ToastNotification.ToastBackColor = Color.Yellow;
            //ToastNotification.ToastForeColor = Color.Black;
        }

        private void HookupEvent()
        {
            var eventAsObservable =
                Observable.FromEventPattern<DevExpress.XtraEditors.Controls.ChangingEventHandler, DevExpress.XtraEditors.Controls.ChangingEventArgs>(
                    ev => textEditProvience.EditValueChanging += ev,
                    ev => textEditProvience.EditValueChanging -= ev)
                    .Where(ev => ev.EventArgs.NewValue != null && ((string)ev.EventArgs.NewValue).Length == 7)
                    .Throttle(TimeSpan.FromSeconds(1));

            eventAsObservable.ObserveOn(SynchronizationContext.Current).Subscribe(LookupVehicle);
        }


        private void LookupVehicle(EventPattern<DevExpress.XtraEditors.Controls.ChangingEventArgs> e)
        {
            _vehicle = GetVehicleByLicenseNumber((string)e.EventArgs.NewValue);
            ShowVehicle();
        }

        private void BeginSession()
        {
            //_vehicle = null;
            //_driver = null;
            //LicenseNumber = null;
            //textEditRoute.EditValue = null;
            //pictureEditVehicle.Image = null;
            //pictureEditDriver.Image = null;
            //textEditDriverName.EditValue = null;
            //textEditDriverQualification.EditValue = null;
            //textEditDriverTestExpire.EditValue = null;
            _unitOfWork = new UnitOfWork();
        }

        private void InitFingerprintReader()
        {

            D5ScannerFPC.EnumDevice();
            _fingerReader = new D5ScannerFPC();
            var suc = _fingerReader.OpenDevice(0);
            if (!suc)
            {
                MessageBox.Show("无法打开指纹仪");
            }
            else
            {
                StartFingerReader();
            }
        }

        private void StartFingerReader()
        {
            _fingerReaderObserver = Observable.Interval(TimeSpan.FromMilliseconds(500))
                       .ObserveOn(SynchronizationContext.Current)
                       .Subscribe(l => ReadFinger());
        }

        private void ReadFinger()
        {
            var img = _fingerReader.GetImage();
            var hasFinger = D5ScannerFPC.CheckFP(img);
            if (hasFinger)
            {
                if (!_fingerOn)
                {
                    _fingerOn = true;
                    var bmp = D5ScannerFPC.ToImage(img);
                    byte[] feature;
                    try
                    {
                        feature = D5ScannerFPC.Process(img);
                        _fingerReader.Beep(40);
                        //ShowToast("指纹采集成功，开始比对");
                        Verify(feature);
                    }
                    catch (Exception ex)
                    {
                        ShowToast("指纹比对失败：" + ex.Message);
                        _retrySoundPlayer.Play();
                    }
                }
            }
            else
            {
                _fingerOn = false;
            }
        }


        private void InitRefreshTimer()
        {
            _timer = Observable.Interval(TimeSpan.FromSeconds(3));
            _refreshObserver = _timer.ObserveOn(SynchronizationContext.Current).Subscribe(_ => LoadWaitingLpr());

        }

        private void LoadWaitingLpr()
        {
            if (collection != null)
            {
                collection.Dispose();
            }
            try
            {
                collection = new XPCollection<RawLprRecord>(_unitOfWork);
                collection.TopReturnedObjects = 20;
                collection.Sorting.Add(new SortProperty("CaptureTime", SortingDirection.Descending));
                collection.Load();
            }
            catch (Exception ex)
            {
                ShowToast("刷新待处理车辆发生错误");
                return;
            }

            Action<XPCollection<RawLprRecord>> ac = c => UpdateTile(collection);
            this.BeginInvoke(ac, collection);

        }

        private void UpdateTile(XPCollection<RawLprRecord> collection)
        {
            tileGroup2.Items.Clear();
            tileControl1.BeginUpdate();
            try
            {
                foreach (var rawLprRecord in collection)
                {
                    var item = new TileItem();
                    try
                    {
                        item.Image = rawLprRecord.Photo;
                    }
                    catch (OutOfMemoryException ex)
                    {
                        _logger.ErrorException("获取图片发生异常", ex);
                        item.Image = null;
                    }

                    var formatString = "{0} " + (rawLprRecord.CaptureTime.Day == DateTime.Now.Day ? "{1:t}" : "{1:MM.dd HH:mm}");
                    item.Text = string.Format(formatString, rawLprRecord.LicensePlateNumber, rawLprRecord.CaptureTime);
                    item.Tag = rawLprRecord;
                    item.ImageScaleMode = TileItemImageScaleMode.ZoomInside;
                    item.ImageAlignment = TileItemContentAlignment.TopCenter;
                    item.TextAlignment = TileItemContentAlignment.BottomLeft;
                    item.ImageToTextAlignment = TileControlImageToTextAlignment.Top;
                    item.ImageToTextIndent = 0;
                    //tileControl1.AppearanceItem.Normal.ForeColor = Color.Black;
                    //tileControl1.ItemAppearance.BackColor = Color.Transparent;
                    tileGroup2.Items.Add(item);
                }
            }
            finally
            {
                tileControl1.EndUpdate();
            }
        }



        private void Form1_Resize(object sender, EventArgs e)
        {

        }

        public void OnComplete(object Capture, string ReaderSerialNumber, Sample Sample)
        {
            var featureSet = ExtractFeatureSet(Sample);
            if (featureSet != null)
            {
                //Action<FeatureSet> ac = Verify;
                //this.BeginInvoke(ac, featureSet);
            }
            else
            {
                ShowToast("指纹采集失败，请重试");

            }
        }

        private void ShowToast(string toast)
        {
            Action<string> ac = s => ToastNotification.Show(this, toast, eToastPosition.MiddleCenter);
            this.BeginInvoke(ac, toast);
        }

        private void Verify(byte[] feature)
        {
            var xpCollection = new XPView(_unitOfWork, typeof(Driver));
            xpCollection.AddProperty("Oid");
            xpCollection.AddProperty("FingerFeature");

            foreach (ViewRecord record in xpCollection)
            {
                var featureToCompare = (byte[])record[1];
                if (featureToCompare != null)
                {
                    var result = D5ScannerFPC.Match(feature, featureToCompare, 180, 4);
                    if (result)
                    {
                        _operationHistory = GetLastOperationHistoryForDriver(record[0]);

                        _driver = GetDriverByKey(record[0]);
                        if (_driver != null && _driver.Vehicle != null)
                        {
                            LicenseNumber = _driver.Vehicle.LicensePlateNumber;
                        }

                        ShowToast("指纹比对成功");
                        _thankYouSoundPlayer.Play();
                        ShowDriver();
                        //ShowVehicle();
                        ShowInfo();
                        return;
                    }
                }
            }

            ShowToast("比对失败，请重试");
            _retrySoundPlayer.Play();
        }

        private TransLogger.Module.BusinessObjects.Vehicle GetVehicleByLicenseNumber(string licenseNumber)
        {
            var collection = new XPCollection<Vehicle>(_unitOfWork);
            collection.Criteria = CriteriaOperator.Parse("LicensePlateNumber = ?", licenseNumber);
            collection.TopReturnedObjects = 1;
            collection.Load();

            return collection.Count > 0 ? collection[0] : null;
        }


        private XPCollection<RawLprRecord> GetOldRawRecord()
        {
            var coll = new XPCollection<RawLprRecord>(_unitOfWork);
            coll.Criteria = CriteriaOperator.Parse("CaptureTime < ?", DateTime.Now.AddHours(-1));
            return coll;
        }

        private XPCollection<RawLprRecord> GetRawRecordByLicenseNumber(string licenseNumber)
        {
            var col = new XPCollection<RawLprRecord>(_unitOfWork);
            col.Criteria = CriteriaOperator.Parse("LicensePlateNumber = ?", licenseNumber);
            return col;
        }

        private TransLogger.Module.BusinessObjects.OperationHistory GetLastOperationHistoryForDriver(object driverOid)
        {
            var collection = new XPCollection<TransLogger.Module.BusinessObjects.OperationHistory>(_unitOfWork);
            collection.Criteria = CriteriaOperator.Parse("[Driver].Oid = ?", driverOid);
            collection.TopReturnedObjects = 1;
            collection.Sorting.Add(new SortProperty("CheckTime", SortingDirection.Descending));
            collection.Load();

            return collection.Count > 0 ? collection[0] : null;
        }

        private TransLogger.Module.BusinessObjects.Driver GetDriverByKey(object driverOid)
        {
            return _unitOfWork.GetObjectByKey<Driver>(driverOid);
        }

        private void ShowInfo()
        {
            Action<TransLogger.Module.BusinessObjects.OperationHistory> ac = h =>
                {
                    this.actualPassengerCount.EditValue = h.PassengerCount;
                    this.textEditFreePassengerCount.EditValue = h.FreePassengerCount;
                    this.tyreState.EditValue = h.TyreState;
                    this.textEditSafetyInstrument.EditValue = h.SafetyInstrument;

                };
            if (_operationHistory != null)
            {
                this.BeginInvoke(ac, _operationHistory);
            }
        }

        private void ShowVehicle()
        {
            Action<Vehicle> ac = v =>
                                     {
                                         // this.textEditLicenseNumber.Text = _vehicle == null ? null : _vehicle.LicensePlateNumber;
                                         this.textEditSmallLicenseNumber.EditValue = _vehicle == null ? null : _vehicle.LicensePlateNumber;

                                         if (_vehicle == null)
                                         {
                                             textEditVehicleType.EditValue = null;
                                         }
                                         else
                                         {
                                             textEditVehicleType.EditValue = _vehicle.VehicleType;
                                         }

                                         if (_vehicle == null)
                                         {
                                             this.textEditTestExpireDate.EditValue = null;
                                         }
                                         else
                                         {
                                             textEditTestExpireDate.EditValue = _vehicle.TestExpireTime;
                                         }

                                         if (_vehicle == null)
                                         {
                                             textEditAllowedPassengerCount.EditValue = null;
                                         }
                                         else
                                         {
                                             textEditAllowedPassengerCount.EditValue = _vehicle.AllowedPassengerCount;
                                         }

                                     };
            this.BeginInvoke(ac, _vehicle);

        }

        private void ShowDriver()
        {
            Action<Driver> ac = d =>
                                    {
                                        this.textEditDriverName.EditValue = _driver;
                                        //this.textEditBigDriverName.Text = _driver.Name;
                                        this.pictureEditDriver.EditValue = _driver.Photo;
                                        this.textEditDriverQualification.EditValue = _driver.DriverQulification;
                                        this.comboBoxEditIdCardNumber.EditValue = _driver;
                                        this.comboBoxEditDriverFileNumber.EditValue = _driver;

                                    };
            this.BeginInvoke(ac, _driver);
        }

        private FeatureSet ExtractFeatureSet(Sample sample)
        {
            var featureExtractor = new DPFP.Processing.FeatureExtraction();
            CaptureFeedback feedback = CaptureFeedback.None;
            FeatureSet featureSet = new FeatureSet();
            featureExtractor.CreateFeatureSet(sample, DataPurpose.Verification, ref feedback, ref featureSet);
            if (feedback == CaptureFeedback.Good)
            {
                return featureSet;
            }

            return null;
        }

        public void OnFingerGone(object Capture, string ReaderSerialNumber)
        {
            //ShowToast("手指离开指纹仪");
        }

        public void OnFingerTouch(object Capture, string ReaderSerialNumber)
        {
            //ShowToast("手指接触指纹仪");
        }

        public void OnReaderConnect(object Capture, string ReaderSerialNumber)
        {
            ShowToast("成功连接指纹仪");
            ShowWarning(null);
        }

        public void OnReaderDisconnect(object Capture, string ReaderSerialNumber)
        {
            ShowWarning("无法连接指纹仪");
        }

        private void ShowWarning(string warning)
        {
            //Action<string> ac = s =>
            //                        {
            //                            layoutControlItemWarning.ContentVisible = !string.IsNullOrEmpty(warning);
            //                            warningBox1.Text = warning;
            //                            warningBox1.Visible = true;
            //                        };
            //this.BeginInvoke(ac, warning);
        }

        public void OnSampleQuality(object Capture, string ReaderSerialNumber, CaptureFeedback CaptureFeedback)
        {
            Debug.WriteLine("connected");
        }

        private void tileControl1_ItemClick(object sender, TileItemEventArgs e)
        {
            var record = e.Item.Tag as RawLprRecord;
            LicenseNumber = record.LicensePlateNumber;
            pictureEditVehicle.Image = record.Photo;

            _vehicle = GetVehicleByLicenseNumber(record.LicensePlateNumber);
            this.ShowVehicle();
        }

        private void simpleButtonOK_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate())
            {
                ShowToast("请先修正填写错误");
                return;
            }

            if (_driver == null)
            {
                ShowToast("请录入指纹，以关联驾驶员");
                return;
            }

            if (!_tyreStates.Contains((string)this.tyreState.EditValue))
            {
                _tyreStates.Add((string)tyreState.EditValue);
                tyreState.Properties.Items.Add(tyreState.EditValue);
            }

            if (!_safetyInstruments.Contains((string)this.textEditSafetyInstrument.EditValue))
            {
                _safetyInstruments.Add((string)this.textEditSafetyInstrument.EditValue);
                textEditSafetyInstrument.Properties.Items.Add(textEditSafetyInstrument.EditValue);
            }

            simpleButtonOK.Enabled = false;
            SaveRecord();
        }

        private void SaveRecord()
        {
            if (_vehicle == null)
            {
                _vehicle = new Vehicle(_unitOfWork);
                _vehicle.LicensePlateNumber = LicenseNumber;
                _vehicle.Drivers.Add(_driver);
            }

            var record = new OperationHistory(_unitOfWork);
            record.Photo = pictureEditVehicle.Image;
            record.Driver = _driver;
            record.Vehicle = _vehicle;
            record.CheckTime = DateTime.Now;
            record.TyreState = tyreState.EditValue.ToString();
            record.SafetyInstrument = textEditSafetyInstrument.EditValue.ToString();
            record.PassengerCount = Convert.ToInt32(actualPassengerCount.EditValue);
            record.FreePassengerCount = Convert.ToInt32(textEditFreePassengerCount.EditValue);
            //record.CheckedBy = _unitOfWork.GetObjectByKey<SecuritySystemUser>(Guid.Parse(Program.CurrentUserId.ToString()));
            record.Save();

            var coll = GetRawRecordByLicenseNumber(LicenseNumber);
            _unitOfWork.Delete(coll);
            _unitOfWork.PurgeDeletedObjects();

            _unitOfWork.CommitChangesAsync(SaveCallback);
        }

        private void SaveCallback(Exception ex)
        {
            _driver = null;
            _vehicle = null;
            ShowToast(ex == null ? "记录保存成功" : ex.Message);


            //Action ac = BeginSession;
            //this.BeginInvoke(ac);
        }

        private void textEditLicenseNumber_EditValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(LicenseNumber) && LicenseNumber.Length == 7)
            {
                _vehicle = GetVehicleByLicenseNumber(LicenseNumber);
                var records = GetRawRecordByLicenseNumber(LicenseNumber);
                pictureEditVehicle.Image = records.Count != 0 ? records[0].Photo : null;
                simpleButtonOK.Enabled = true;
            }
            else
            {
                _vehicle = null;
            }

            ShowVehicle();

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_refreshObserver != null)
            {
                _refreshObserver.Dispose();
            }

            if (_fingerReaderObserver != null)
            {
                _fingerReaderObserver.Dispose();
            }

            if (_fingerReader != null)
            {
                _fingerReader.Dispose();
            }


            File.WriteAllLines(SafetyInstrumentFilePath, _safetyInstruments);
            File.WriteAllLines(TyreStateFilePath, _tyreStates);

            var szConverter = TypeDescriptor.GetConverter(typeof(Size));

            var szStr = szConverter.ConvertToString(_popupActualPassengerCount.Size);
            Properties.Settings.Default.NumberOnlyKeyboardSize = szStr;
            var szNumChar = szConverter.ConvertToString(_popupLprNumber.Size);
            Properties.Settings.Default.NumberKeyboardSize = szNumChar;

            Properties.Settings.Default.Save();
        }

        private void comboBoxEditIdCardNumber_EditValueChanged(object sender, EventArgs e)
        {
            _driver = comboBoxEditIdCardNumber.EditValue as Driver;
            ShowDriver();
        }

        private void comboBoxEditDriverFileNumber_EditValueChanged(object sender, EventArgs e)
        {
            _driver = comboBoxEditDriverFileNumber.EditValue as Driver;
            ShowDriver();
        }

        private void textEditDriverName_EditValueChanged(object sender, EventArgs e)
        {
            _driver = textEditDriverName.EditValue as Driver;
            ShowDriver();
        }

        private void simpleButtonReloadDrivers_Click(object sender, EventArgs e)
        {
            LoadDrivers();
        }
    }
}